<template>
  <!-- eslint-disable-next-line -->
  <div ref="w-custom-markdown-parsing" class="w-custom-markdown-parsing" v-html="markedown" @copy="copyChange"/>
</template>

<script lang="ts">
import hljs from 'highlight.js'
import Marked from 'marked'
import { Vue, Component, Prop, Watch } from 'vue-property-decorator'

@Component({
  name: 'MarkedCustomSprsing'
})
export default class MarkedCustomSprsing extends Vue {
  // 传入的MarkDown数据
  @Prop({ type: String, default: '' }) datastr!: string

  // 解析的数据
  markedown = ''
  // marked解析对象
  marked = new Marked.Renderer()
  // 定时器（缓存数据转换）
  timer: NodeJS.Timeout | null = null

  @Watch('datastr')
  datastrChange () {
    this.createTimer()
  }

  created () {
    this.initMarked()
    this.markedown = this.targrtBlank(Marked(this.datastr))
  }

  beforeDestroy () {
    this.clearTimer()
  }

  /**
   * 给a标签加上 target="_blank"
   */
  targrtBlank (str: string) {
    if (str && str.length > 0) {
      return str.replace(/<a /g, '<a target="_blank" ')
    }
    return ''
  }

  /**
   * 初始化解析对象
   */
  initMarked () {
    const rendererMD = new Marked.Renderer()
    Marked.setOptions({
      renderer: rendererMD,
      gfm: true,
      breaks: false,
      pedantic: false,
      sanitize: false,
      smartLists: true,
      smartypants: false
    })
    Marked.setOptions({
      highlight: (code) => {
        return hljs.highlightAuto(code).value
      }
    })
  }

  /**
   * 创建定时器
   * @param oldVal 旧数据
   */
  createTimer () {
    this.clearTimer()
    this.timer = setTimeout(() => {
      this.markedown = this.targrtBlank(Marked(this.datastr))
    }, 500)
  }

  /**
   * 清除定时器
   */
  clearTimer () {
    if (this.timer) {
      clearTimeout(this.timer)
      this.timer = null
    }
  }

  copyChange () {
    const copyText = (window.getSelection() as any).toString()
    this.$wCopy(copyText)
    // this.$wCopy(`${copyText}
    // // 作者：王亚彬
    // // 网站：https://wangyabin.top
    // `)
  }
}
</script>

<style lang="less">
@import '../../../../../assets/css/marked';
@import '../../../../../node_modules/highlight.js/styles/xcode.css';
.w-custom-markdown-parsing {
  padding: 0 5px;
}
</style>
